package cn.dakaqi.web;

import cn.dakaqi.web.shiro.ShiroDbRealm;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by chunyang on 2016/5/17.
 */
@RestController
@RequestMapping(value = "/center")
@Slf4j
public class IndexController extends BaseController
{
//    @RequestMapping(method = RequestMethod.GET)
//    public RedirectView index(HttpServletRequest request,RedirectAttributes redirectAttributes)
//    {
//        Long userId = this.getCurrentUserId();
//        if(null == userId || userId == 0L)
//        {
//            log.info("这里是网站的首页");
//            String url = request.getContextPath()+"/";
//            log.info(url);
//            return new RedirectView(url);
//        }
//        else
//        {
//            String url = request.getContextPath()+ "/dashboard";
//            return new RedirectView(url);
//        }

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView index(HttpServletRequest request)
    {
        Long userId = this.getCurrentUserId();
        if(null == userId || userId == 0L)
        {
            log.info("这里是网站的首页");
            ModelAndView modelAndView = new ModelAndView("index2");
            return modelAndView;
        }
        else
        {
            String view = "dashboard/index";
            modelAndView = initModelAndView("", view,request);
            modelAndView.getModelMap();
            return modelAndView;
        }
    }

    @Override
    protected ModelAndView initModelAndView(String groupCode, String view,HttpServletRequest request)
    {
        ModelMap modelMap = super.initData(groupCode,request);
        return new ModelAndView(view,modelMap);
    }

    @Override
    protected void clearModelAndView(String groupCode,HttpServletRequest request)
    {

    }

    /**
     * 取出Shiro中的当前用户Id.
     */
    private Long getCurrentUserId() {
        ShiroDbRealm.ShiroUser user = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        if(null != user)
            return user.id;
        else
            return null;
    }

    /**
     * 更新Shiro中当前用户的用户名.
     */
    private void updateCurrentUserName(String userName) {
        ShiroDbRealm.ShiroUser user = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        if(null != user)
            user.realName = userName;

    }

}
